package com.junt.library.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.junt.library.MediaSelector;
import com.junt.library.R;
import com.junt.library.model.Directory;
import com.junt.library.model.Media;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

public class DirAdapter extends RecyclerView.Adapter<DirAdapter.DirViewHolder> {
    private List<Directory> directories;
    private OnDirectorySelectedListener listener;

    public DirAdapter(OnDirectorySelectedListener listener) {
        this.listener = listener;
        directories = new ArrayList<>();
    }

    @NonNull
    @Override
    public DirViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new DirViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_dir_popup, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull DirViewHolder holder, int position) {
        final Directory directory = directories.get(position);
        MediaSelector.getInstance().getImageEngine().load(directory.getCoverUri(), holder.imageView);
        holder.tvDir.setText(directory.getText());
        holder.tvNum.setText(String.format(Locale.getDefault(), "(%d)", directory.getChildSize()));
        holder.ivSelectedStatus.setVisibility(directory.getText().equals(listener.getSelectedDir())?View.VISIBLE:View.GONE);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notifyDataSetChanged();
                listener.onDirSelected(directory);
            }
        });
    }

    @Override
    public int getItemCount() {
        return directories.size();
    }

    public void setNewData(Map<String, List<Media>> dirMap) {
        directories.clear();

        for (Map.Entry<String, List<Media>> entry : dirMap.entrySet()) {
            List<Media> value = entry.getValue();
            directories.add(new Directory(entry.getKey(), value.get(0).getUri(), value.size()));
        }
        notifyDataSetChanged();
    }

    class DirViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView,ivSelectedStatus;
        private TextView tvDir, tvNum;

        public DirViewHolder(@NonNull View itemView) {
            super(itemView);
            imageView = itemView.findViewById(R.id.imageView);
            ivSelectedStatus = itemView.findViewById(R.id.ivSelectedStatus);
            tvDir = itemView.findViewById(R.id.tvDir);
            tvNum = itemView.findViewById(R.id.tvNum);
        }
    }

    public interface OnDirectorySelectedListener {
        void onDirSelected(Directory directory);
        String getSelectedDir();
    }
}
